import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Input, Select, Space, message, List, Tag, Typography, Empty } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined, ApiOutlined } from '@ant-design/icons';
import { AgentPluginConfig, Plugin, PluginParameter } from '../types';
import { useTranslation } from 'react-i18next';

const { Text } = Typography;

interface PluginConfigurationProps {
  plugins: Plugin[];
  value?: AgentPluginConfig[];
  onChange?: (configs: AgentPluginConfig[]) => void;
}

const PluginConfiguration: React.FC<PluginConfigurationProps> = ({ plugins, value = [], onChange }) => {
  const { t } = useTranslation();
  const [configurations, setConfigurations] = useState<AgentPluginConfig[]>(value);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [selectedPlugin, setSelectedPlugin] = useState<Plugin | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    setConfigurations(value);
  }, [value]);

  const parseParameterDefinitions = (paramDefs: any): PluginParameter[] => {
    if (!paramDefs) {
      return [];
    }

    // 如果是字符串，尝试解析 JSON
    if (typeof paramDefs === 'string') {
      try {
        const parsed = JSON.parse(paramDefs);
        return Array.isArray(parsed) ? parsed : [];
      } catch (error) {
        console.warn('Failed to parse parameterDefinitions JSON:', error);
        return [];
      }
    }

    // 如果已经是数组，直接返回
    if (Array.isArray(paramDefs)) {
      return paramDefs;
    }

    return [];
  };

  const openModal = (index?: number) => {
    if (index !== undefined) {
      const config = configurations[index];
      const plugin = plugins.find(p => p.id === config.pluginId);
      if (plugin) {
        // 解析 parameterDefinitions 确保它是数组
        const parsedPlugin = {
          ...plugin,
          parameterDefinitions: parseParameterDefinitions(plugin.parameterDefinitions),
        };
        setSelectedPlugin(parsedPlugin);
      } else {
        setSelectedPlugin(null);
      }
      setEditingIndex(index);

      form.setFieldsValue({
        pluginId: config.pluginId,
        authToken: config.authToken,
        endpoint: config.endpoint,
        ...config.parameterValues,
      });
    } else {
      setEditingIndex(null);
      setSelectedPlugin(null);
      form.resetFields();
    }
    setModalVisible(true);
  };

  const closeModal = () => {
    setModalVisible(false);
    setEditingIndex(null);
    setSelectedPlugin(null);
    form.resetFields();
  };

  const handlePluginChange = (pluginId: number) => {
    const plugin = plugins.find(p => p.id === pluginId);
    if (plugin) {
      // 解析 parameterDefinitions 确保它是数组
      const parsedPlugin = {
        ...plugin,
        parameterDefinitions: parseParameterDefinitions(plugin.parameterDefinitions),
      };
      setSelectedPlugin(parsedPlugin);
    } else {
      setSelectedPlugin(null);
    }
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      const { pluginId, authToken, endpoint, ...parameterValues } = values;

      const config: AgentPluginConfig = {
        pluginId,
        authToken: authToken || undefined,
        endpoint: endpoint || undefined,
        parameterValues: Object.keys(parameterValues).length > 0 ? parameterValues : undefined,
      };

      let newConfigurations;
      if (editingIndex !== null) {
        newConfigurations = [...configurations];
        newConfigurations[editingIndex] = config;
      } else {
        newConfigurations = [...configurations, config];
      }

      setConfigurations(newConfigurations);
      onChange?.(newConfigurations);
      closeModal();
      message.success(t(editingIndex !== null ? 'agent.pluginConfigUpdated' : 'agent.pluginConfigAdded'));
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleDelete = (index: number) => {
    const newConfigurations = configurations.filter((_, i) => i !== index);
    setConfigurations(newConfigurations);
    onChange?.(newConfigurations);
    message.success(t('agent.pluginConfigRemoved'));
  };

  const getPluginName = (pluginId: number) => {
    const plugin = plugins.find(p => p.id === pluginId);
    return plugin?.name || `Plugin #${pluginId}`;
  };

  const needsEndpoint = selectedPlugin && !selectedPlugin.endpoint;

  const getPluginTypeColor = (type: string) => {
    const colorMap: Record<string, string> = {
      api: 'blue',
      webhook: 'green',
      database: 'orange',
      storage: 'purple',
      ai: 'cyan',
    };
    return colorMap[type.toLowerCase()] || 'default';
  };

  return (
    <div>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text type="secondary">
            {configurations.length > 0 
              ? `${t('agent.totalPlugins')}: ${configurations.length}`
              : t('agent.noPlugins')}
          </Text>
          <Button type="primary" onClick={() => openModal()} icon={<PlusOutlined />}>
            {t('agent.addPluginConfig')}
          </Button>
        </div>

        {configurations.length === 0 ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={t('agent.noPluginsDescription')}
            style={{ padding: '40px 0' }}
          />
        ) : (
          <List
            bordered
            dataSource={configurations}
            renderItem={(config, index) => {
              const plugin = plugins.find(p => p.id === config.pluginId);
              return (
                <List.Item
                  style={{ 
                    padding: '16px 24px',
                    transition: 'background-color 0.3s',
                    cursor: 'pointer',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.backgroundColor = '#fafafa';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.backgroundColor = 'transparent';
                  }}
                  actions={[
                    <Button
                      key="edit"
                      type="text"
                      icon={<EditOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        openModal(index);
                      }}
                    >
                      {t('common.edit')}
                    </Button>,
                    <Button
                      key="delete"
                      type="text"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDelete(index);
                      }}
                    >
                      {t('common.delete')}
                    </Button>,
                  ]}
                  onClick={() => openModal(index)}
                >
                  <List.Item.Meta
                    avatar={
                      <div
                        style={{
                          width: 40,
                          height: 40,
                          borderRadius: '8px',
                          backgroundColor: '#722ed1', // Purple for plugins
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          color: '#fff',
                          fontSize: '18px',
                        }}
                      >
                        <ApiOutlined />
                      </div>
                    }
                    title={
                      <Space size="middle">
                        <Text strong style={{ fontSize: '16px' }}>
                          {getPluginName(config.pluginId)}
                        </Text>
                        {plugin && (
                          <Tag color={getPluginTypeColor(plugin.pluginType)}>
                            {plugin.pluginType.toUpperCase()}
                          </Tag>
                        )}
                        {config.authToken && (
                          <Tag color="gold">{t('agent.authenticated')}</Tag>
                        )}
                      </Space>
                    }
                    description={
                      <Space direction="vertical" size="small" style={{ width: '100%', marginTop: '8px' }}>
                        {plugin?.description && (
                          <div>
                            <Text type="secondary" style={{ fontSize: '13px' }}>
                              {plugin.description}
                            </Text>
                          </div>
                        )}
                        {config.endpoint && (
                          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <Text type="secondary" style={{ fontSize: '12px' }}>
                              {t('agent.endpoint')}:
                            </Text>
                            <Text code style={{ fontSize: '12px' }}>
                              {config.endpoint}
                            </Text>
                          </div>
                        )}
                        {config.parameterValues && Object.keys(config.parameterValues).length > 0 && (
                          <div>
                            <Tag color="processing">
                              {t('agent.parametersConfigured', { count: Object.keys(config.parameterValues).length })}
                            </Tag>
                          </div>
                        )}
                      </Space>
                    }
                  />
                </List.Item>
              );
            }}
          />
        )}
      </Space>

      <Modal
        title={editingIndex !== null ? t('agent.editPluginConfig') : t('agent.addPluginConfig')}
        open={modalVisible}
        onOk={handleSave}
        onCancel={closeModal}
        width={600}
        okText={t('common.save')}
        cancelText={t('common.cancel')}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="pluginId"
            label={t('agent.plugin')}
            rules={[{ required: true, message: t('agent.pluginRequired') }]}
          >
            <Select
              placeholder={t('agent.pluginPlaceholder')}
              onChange={handlePluginChange}
              disabled={editingIndex !== null}
            >
              {plugins.map(plugin => (
                <Select.Option key={plugin.id} value={plugin.id}>
                  {plugin.name} ({plugin.pluginType})
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          {selectedPlugin && (
            <>
              {needsEndpoint && (
                <Form.Item
                  name="endpoint"
                  label={t('agent.endpointUrl')}
                  rules={[
                    { required: true, message: t('agent.endpointRequired') },
                    { type: 'url', message: t('agent.endpointInvalidUrl') },
                  ]}
                >
                  <Input placeholder="https://api.example.com/plugin" />
                </Form.Item>
              )}

              {selectedPlugin.authMethod !== 'none' && (
                <Form.Item
                  name="authToken"
                  label={`${t('agent.authToken')} (${selectedPlugin.authMethod})`}
                  rules={[{ required: true, message: t('agent.authTokenRequired') }]}
                >
                  <Input.Password placeholder={t('agent.authTokenPlaceholder')} />
                </Form.Item>
              )}

              {selectedPlugin.parameterDefinitions && 
               Array.isArray(selectedPlugin.parameterDefinitions) && 
               selectedPlugin.parameterDefinitions.length > 0 && (
                <>
                  <div style={{ marginTop: 16, marginBottom: 8, fontWeight: 'bold' }}>
                    {t('agent.pluginParameters')}:
                  </div>
                  {selectedPlugin.parameterDefinitions.map((param: PluginParameter) => (
                    <Form.Item
                      key={param.name}
                      name={param.name}
                      label={
                        <Space>
                          {param.name}
                          {param.required && <Tag color="red">{t('plugin.required')}</Tag>}
                        </Space>
                      }
                      rules={[
                        {
                          required: param.required,
                          message: t('agent.parameterRequired', { name: param.name }),
                        },
                      ]}
                      tooltip={param.description}
                    >
                      {param.type === 'boolean' ? (
                        <Select>
                          <Select.Option value={true}>{t('common.true')}</Select.Option>
                          <Select.Option value={false}>{t('common.false')}</Select.Option>
                        </Select>
                      ) : param.type === 'number' ? (
                        <Input type="number" placeholder={t('agent.parameterPlaceholder', { name: param.name })} />
                      ) : param.type === 'object' ? (
                        <Input.TextArea rows={3} placeholder={t('agent.jsonObjectPlaceholder')} />
                      ) : (
                        <Input placeholder={t('agent.parameterPlaceholder', { name: param.name })} />
                      )}
                    </Form.Item>
                  ))}
                </>
              )}
            </>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default PluginConfiguration;
